package com.tfswue.jqr.config;

import com.tfswue.jqr.entity.Book;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class RedisConfig {
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory){
        // 添加默认配置（30分钟）
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30));

        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        // 为特定缓存设置独立过期时间
//        configMap.put("dataCache",
//                RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)));// 1小时

        configMap.put("dataCache",
                RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(1)));// 1分钟

//        configMap.put("productCache",
//                RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)));// 10分钟

        return RedisCacheManager.builder(factory)
                .cacheDefaults(defaultConfig)
                .withInitialCacheConfigurations(configMap)
                .build();
    }

    @Bean
    public RedisTemplate<String, Book> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Book> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // 支持 Book 序列化
        return template;
    }
}
